package com.GLM.Viewer.Friends;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.GLM.Constants.Constant;
import com.GLM.Entity.FriendsGroupEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Viewer.R;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.text.InputType;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class FriendsGroupsActivity extends Activity {
	private final static int GROUP_LOADING = 111;
	private final static int GROUP_LONDED = 222;
	private ListView mGroupList;
	private SimpleAdapter mGroupsAdapter;
	private List<Map<String, Object>> mGroupItems = new ArrayList<Map<String, Object>>();
	private String[] groupItemKeys = new String[] { "GroupName","GroupMemNum" };
	private int[] groupItemIds = new int[] { R.id.friends_group_name,R.id.friends_group_count };
	Animation mAnimIn;
	Animation mAnimOut;
	private Map<Integer, FriendsGroupEntity> groupsMap = new HashMap<Integer, FriendsGroupEntity>();
	View mInputFieldOneLine;
	TextView mInputFieldOneLineTextView;
	EditText mInputFieldOneLineEditText;
	InputMethodManager imm;
	private int screenWidth;
	private int screenHeight;
	RelativeLayout layout;
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			Thread thread;
			
			switch (msg.what) {
			case GROUP_LOADING:
				thread = new Thread(new Runnable() {
					public void run() {
						
						initFriendsGroup();
						mGroupsAdapter = new SimpleAdapter(FriendsGroupsActivity.this, mGroupItems, R.layout.view_friends_mygroup_item,groupItemKeys, groupItemIds);
						mHandler.sendEmptyMessage(GROUP_LONDED);
					}

				});
				thread.start();
				break;
			case GROUP_LONDED:
				if(mGroupsAdapter != null && mGroupItems.size()>0){
					mGroupList.setAdapter(mGroupsAdapter);
					
					bindItemClick();
				}else{
					Paint paint = new Paint();
					paint.setTextSize(20);
					paint.setAntiAlias(true);
					String str = getString(R.string.friends_no_groups);
					Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.glm_background);
					Canvas canvas = new Canvas(bitmap);
					canvas.drawText(str,screenWidth/2-str.length()*9 , screenHeight/2, paint);
					layout = (RelativeLayout)findViewById(R.id.friends_mygroup_layout);
					Drawable drawable = new BitmapDrawable(bitmap);
					layout.setBackgroundDrawable(drawable);
				}
				break;
			default:
				break;
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_friends_mygroup);
		screenWidth = getWindowManager().getDefaultDisplay().getWidth();
		screenHeight = getWindowManager().getDefaultDisplay().getHeight();
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		initInputFields();
		initAnimation();
		mGroupList = (ListView)findViewById(R.id.friends_myfriends_groupslist);
		initRegisterInputFieldButton();
		final SharedPreferences sp = getSharedPreferences(Constant.SHAREDNAME, MODE_PRIVATE);
		boolean isshow = sp.getBoolean(Constant.FRIENDGROUPACTIVITY, true);
		final ImageView tipView = (ImageView)findViewById(R.id.tipView);
		if(!isshow){
			tipView.setVisibility(View.VISIBLE);
			tipView.setOnTouchListener(new OnTouchListener() {
				
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					tipView.setVisibility(View.INVISIBLE);
					tipView.setImageBitmap(null);
					Editor editor = sp.edit();
					editor.putBoolean(Constant.FRIENDGROUPACTIVITY, true);
					editor.commit();
					System.gc();
					return true;
				}
			});
		}
		mHandler.sendEmptyMessage(GROUP_LOADING);
	}
	
	private void initInputFields() {
		mInputFieldOneLine = findViewById(R.id.inputfield_oneline);
		mInputFieldOneLine.setVisibility(View.GONE);
		mInputFieldOneLineTextView = (TextView) findViewById(R.id.inputfield_title);
		mInputFieldOneLineEditText = (EditText) findViewById(R.id.inputfield_edittext);

	}
	
	private void initAnimation() {
		mAnimIn = AnimationUtils.loadAnimation(this, R.anim.anim_register_in);
		mAnimOut = AnimationUtils.loadAnimation(this, R.anim.anim_register_out);
	}
	
	
	private void showOneLineInputField() {
		mInputFieldOneLine.startAnimation(mAnimIn);
		mInputFieldOneLine.setVisibility(View.VISIBLE);
		mInputFieldOneLineTextView.setText(getString(R.string.friends_myfriends_groupname));
		mInputFieldOneLineEditText.requestFocus();
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	private void hideOneLineInputField() {
		mInputFieldOneLineEditText.setText("");
		mInputFieldOneLineEditText.setInputType(InputType.TYPE_NULL);
		mInputFieldOneLineEditText.clearFocus();
		mInputFieldOneLine.startAnimation(mAnimOut);
		mInputFieldOneLine.setVisibility(View.GONE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
		
	}
	
	private void initRegisterInputFieldButton() {
		// one line
		Button inputCancelButton = (Button) findViewById(R.id.inputfield_cancelbutton);
		inputCancelButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				hideOneLineInputField();
			}
		});

		Button inputOkButton = (Button) findViewById(R.id.inputfield_okbutton);
		inputOkButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				String groupName = mInputFieldOneLineEditText.getText().toString().trim();
				if(groupName != null){
					hideOneLineInputField();
					int status = initCheckUserState(34, groupName);
					if(status == 2){
						status = initCheckUserState(35, groupName);
						if(status == 2){
							Toast.makeText(FriendsGroupsActivity.this, getString(R.string.friends_groups_create_success), Toast.LENGTH_LONG).show();
							layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.glm_background));
							mGroupItems.clear();
							initFriendsGroup();
							mGroupsAdapter = new SimpleAdapter(FriendsGroupsActivity.this, mGroupItems, R.layout.view_friends_mygroup_item,groupItemKeys, groupItemIds);
							mGroupList.setAdapter(mGroupsAdapter);
						}
					}
				}
			}
		});
	}
	
	public int initCheckUserState(int way,String groupName){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		int state = -1;
		try {
			jsonData.put(Constant.PARAM_USERID, UserInfoDAO.getUserInfo(FriendsGroupsActivity.this).getUserId());
			jsonData.put(Constant.PARAM_GROUP_RGNAME, groupName);
			jsonResponse = JSONUtil.postRequest(way, jsonData);
			if(jsonResponse.getStatus() != Status.ERR){
				JSONObject data = jsonResponse.getData();
				state = data.getInt(Constant.RESP_STATUS);
				
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		return state;
	}
	
	
	
	public void initFriendsGroup(){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_USERID, UserInfoDAO.getUserInfo(FriendsGroupsActivity.this).getUserId());
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETFRIENDSGROUPS, jsonData);
			if(jsonResponse.getStatus() != Status.ERR){
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				if(status == Constant.RESP_STATUS_SUCCESS){
					JSONArray jsonArray = data.getJSONArray(Constant.RESP_FRIENDS_GROUPS);
					String[] ss = JSONUtil.JSONStringArrayToStringArray(jsonArray);
					for(int i=0; i<ss.length; i++){
						Log.d("friendsGroup", ss[i]);
					}
					initGroupsFromJSONObject(jsonArray);
				}
				
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	public void bindItemClick(){
		mGroupList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long id) {
				// TODO Auto-generated method stub
				FriendsGroupEntity entity = groupsMap.get(position);
				int rg_id = entity.getRg_id();
				Intent intent = new Intent(FriendsGroupsActivity.this,FriendsGroupDetailActivity.class);
				
				intent.putExtra("rg_id", rg_id);
				intent.putExtra("groupName", entity.getRg_name());
				startActivity(intent);
			}
		});
	}
	
	public void goBackButton_OnClick(View v){
		NavUtils.navigateUpFromSameTask(FriendsGroupsActivity.this);
	}
	
	
	public void createNewGroup(View v){
		showOneLineInputField();
	}
	private void initGroupsFromJSONObject(JSONArray jsonArray) throws JsonSyntaxException, JSONException {
		Gson gson = new Gson();
		for (int i = 0; i < jsonArray.length(); i++) {
			FriendsGroupEntity entity = gson.fromJson(jsonArray.getJSONObject(i).toString(), FriendsGroupEntity.class);
			Map<String, Object> item = new HashMap<String, Object>();
			
			item.put("GroupName", entity.getRg_name());
			item.put("GroupMemNum", entity.getRg_count());
			
			mGroupItems.add(item);
			groupsMap.put(i, entity);
		}
		
	}
}
	
	
